package nash.data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import nash.model.NashChange;
import nash.model.Person;
import nash.model.SituationChange;

public class StaticDataController {

    static EntityManagerFactory emfInstance = Persistence.createEntityManagerFactory("nash");

    public synchronized static List<Person> getAllPeople() {
        EntityManager em = emfInstance.createEntityManager();
        List<Person> listOfPeople = em.createQuery("SELECT x FROM Person x").getResultList();
        em.close();
        return listOfPeople;
    }

    public synchronized static List<NashChange> getAllNashMessages() {
        EntityManager em = emfInstance.createEntityManager();
        List<NashChange> listOfPeople = em.createQuery("SELECT x FROM NashChange x").getResultList();
        Collections.sort(listOfPeople, new Comparator() {

            @Override
            public int compare(Object o1, Object o2) {
                return ((NashChange) o2).getTimestamp().compareTo(((NashChange) o1).getTimestamp());
            }
        });
        em.close();
        return listOfPeople;
    }

    public synchronized static List<SituationChange> getAllSituationMessages() {
        EntityManager em = emfInstance.createEntityManager();
        List<SituationChange> listOfPeople = em.createQuery("SELECT x FROM SituationChange x").getResultList();
        em.close();
        Collections.sort(listOfPeople, new Comparator() {

            @Override
            public int compare(Object o1, Object o2) {
                return ((SituationChange) o2).getTimestamp().compareTo(((SituationChange) o1).getTimestamp());
            }
        });
        return listOfPeople;
    }

    public static Person createPerson(Person person) {
        createPersistThread(person);
        return person;
    }

    public static Person updatePerson(Person person) {
        EntityManager em = emfInstance.createEntityManager();
        Person p = em.find(Person.class, person.getId());
        p.setType(person.getType());
        em.getTransaction().begin();
        em.persist(p);
        em.getTransaction().commit();
        em.close();
        return person;
    }

    public static Object createMessage(Object message) {
        createPersistThread(message);
        return message;
    }

    private synchronized static Object createPersistThread(Object object) {
        EntityManager em = emfInstance.createEntityManager();
        em.getTransaction().begin();
        em.persist(object);
        em.getTransaction().commit();
        em.close();
        return object;
    }
}
